<?php
declare (strict_types=1);

namespace app\store\model\question;

use app\common\model\questionnaire\Topic as Model;
use app\store\model\UploadFile as UploadFileModel;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\db\exception\DbException;
use think\Paginator;

class Topic extends Model
{
    /**
     * 获取用户列表
     * @param array $param
     * @return Paginator
     * @throws DbException
     */
    public function getList($param = [])
    {
        // 查询模型
        $query = $this->getNewQuery();
        // 查询参数
        $filter = $this->getQueryFilter($param);

        if (!empty($param['export']) && $param['export'] == 1) {
            $list = $query
                ->where($filter)
                ->where('is_delete', '=', '0')
                ->order(['create_time' => 'desc'])
                ->select();
            $this->baseExport('导出Excel' . date('YmdHis'), $list);
        }
        // 查询列表记录
        $list = $query
            ->where($filter)
            ->where('is_delete', '=', '0')
            ->order(['create_time' => 'desc'])
            ->paginate(15);
        return $list;
    }

    public function getQueryFilter($param)
    {
        $params = $this->setQueryDefaultValue($param, [
            'title' => '',
            'qt_type' => '',
            'question_id' => '',
        ]);

        $filter = [];
        !empty($params['title']) && $filter[] = ["title", "like", "%{$params['title']}%"];
        !empty($params['qt_type']) && $filter[] = ["qt_type", "=", $params['qt_type']];
        !empty($params['question_id']) && $filter[] = ["question_id", "=", $params['question_id']];

        if (!empty($params['create_time'])) {
            $times = between_time($params['create_time']);
            $filter[] = ['create_time', '>=', $times['start_time']];
            $filter[] = ['create_time', '<', $times['end_time'] + 86400];
        }
        return $filter;
    }

    /**
     * 增加记录
     * @param array $data
     * @return bool
     */
    public function add($data)
    {
        $data['store_id'] = self::$storeId;

        if (!empty($data['qt_item'])) {
            $data['qt_item'] = json_encode($data['qt_item'], 320);
        }

        return $this->save($data);
    }

    /**
     * 更新记录
     * @param array $data
     * @return bool
     */
    public function edit(array $data)
    {
        if (!empty($data['qt_item'])) {
            $data['qt_item'] = json_encode($data['qt_item'], 320);
        }
        return $this->save($data);
    }


    /**
     * 软删除
     * @return false|int
     */
    public function setDelete()
    {
        return $this->save(['is_delete' => 1]);
    }

    public function importExcel($fileId, $question_id)
    {
        $file = UploadFileModel::detail($fileId);
        if (!$file) {
            $this->error = '文件不存在';
            return false;
        }
        $filePath = ROOT_PATH() . '/public/uploads/' . $file->file_path;
        $spreadsheet = IOFactory::load($filePath);
        $list = $spreadsheet->getActiveSheet()->toArray();

        $error = "";
        $add_data = [];
        foreach ($list as $index => $item) {
            if ($index > 0) {
                $data = [
                    'question_id' => $question_id,
                    'is_delete' => 0,
                    'store_id' => self::$storeId,
                ];
                $line = $index + 1;

                $title = !empty($item[0]) ? trim((string)$item[0]) : '';
                if ($title) {
                    $data["title"] = $title;
                } else {
                    $error = "第{$line}行错误：题目标题不能为空！";
                    break;
                }

                $qt_type = !empty($item[1]) ? trim((string)$item[1]) : '';
                if ($title) {
                    $arr = [
                        '判断题' => 1,
                        '单选题' => 2,
                        '多选题' => 3,
                    ];
                    if (empty($arr[$qt_type])) {
                        $error = "第{$line}行错误：题目类型为空或者格式错误！";
                        break;
                    }
                    $data["qt_type"] = $arr[$qt_type];
                } else {
                    $error = "第{$line}行错误：题目类型不能为空！";
                    break;
                }

                $answer = !empty($item[2]) ? trim((string)$item[2]) : '';
                if ($answer) {
                    $answer = str_split($answer);
                    sort($answer);
                    $answer = implode(',', $answer);
                    $data["answer"] = $answer;
                } else {
                    $error = "第{$line}行错误：正确答案不能为空！";
                    break;
                }

                $score = !empty($item[3]) ? trim((string)$item[3]) : '';
                if ($score) {
                    $data["score"] = $score;
                } else {
                    $error = "第{$line}行错误：分数不能为空！";
                    break;
                }
                $ho = [
                    4 => 'A',
                    5 => 'B',
                    6 => 'C',
                    7 => 'D',
                    8 => 'E',
                ];
                $qt_item = [];
                for ($i = 4; $i <= 8; $i++) {
                    $value = !empty($item[$i]) ? trim((string)$item[$i]) : '';
                    if ($value) {
                        $qt_item[] = [
                            'item' => $ho[$i],
                            'value' => $value,
                        ];
                    }
                }

                $data["qt_item"] = json_encode($qt_item, 320);
                $add_data[] = $data;
            }
        }

        if ($error) {
            $this->error = $error;
            return false;
        }

        $this->saveAll($add_data);
        return true;
    }


    public function autoadd($data)
    {
        $add_data = [];
        foreach ($data as $item) {
            if (!empty($item['answer'] && strpos($item['answer'], ',') !== false)) {
                $item['answer'] = explode(',', $item['answer']);
                sort($item['answer']);
                $item['answer'] = implode(',', $item['answer']);
            }

            $add_data[] = [
                'store_id' => self::$storeId,
                'question_id' => $item['question_id'],
                'title' => $item['title'],
                'qt_type' => $item['qt_type'],
                'answer' => $item['answer'],
                'score' => $item['score'],
                'qt_item' => json_encode($item['qt_item'], 320)
            ];
        }

        return $this->saveAll($add_data);
    }
}
